package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.EmpService;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.awt.print.Book;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        Emp e = empService.login(emp);
        if (e != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("username", e.getUsername());
            claims.put("name", e.getName());

            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误，登录失败");
    }


    @Autowired
    private UserService userService;

    /**
     * 登录操作，返回令牌
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public Result login(String username,String password){
        User user = userService.login(username,password);
        if (user != null){
            Map<String,Object> mes = new HashMap<>();
            mes.put("id",user.getId());
            String jwt = JwtUtils.generateJwt(mes);
            return Result.success(jwt);
        }
        return Result.error("NOT_LOGIN");
    }
}
